package com.lcq.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.lcq.common.constant.CartConstant;
import com.lcq.common.utils.R;
import com.lcq.gulimall.cart.feign.ProductFeignService;
import com.lcq.gulimall.cart.interceptor.CartInterceptor;
import com.lcq.gulimall.cart.service.CartService;
import com.lcq.gulimall.cart.vo.Cart;
import com.lcq.gulimall.cart.vo.CartItem;
import com.lcq.gulimall.cart.vo.SkuInfoVo;
import com.lcq.gulimall.cart.vo.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public CartItem addSku(Long skuId, Integer count) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> boundHashOps = createBoundHashOps();
        String cartItemStr = (String) boundHashOps.get(skuId.toString());
        CartItem cartItem = null;
        if (StringUtils.isEmpty(cartItemStr)){
            cartItem = createItem(skuId, count);
        }else {
            cartItem = updateItem(cartItemStr, count);
        }

        cartItemStr = JSON.toJSONString(cartItem);
        boundHashOps.put(skuId.toString(),cartItemStr);
        return cartItem;
    }

    public void addCartItem(CartItem item){
        BoundHashOperations<String, Object, Object> boundHashOps = createBoundHashOps();
        String cartItemStr = (String) boundHashOps.get(item.getSkuId().toString());

        if (!StringUtils.isEmpty(cartItemStr)){
            item = updateItem(cartItemStr, item.getCount());
        }

        cartItemStr = JSON.toJSONString(item);
        boundHashOps.put(item.getSkuId().toString(),cartItemStr);
    }



    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> boundHashOps = createBoundHashOps();
        String cartItemStr = (String) boundHashOps.get(skuId.toString());
        return JSON.parseObject(cartItemStr, new TypeReference<CartItem>(){});
    }

    @Override
    public Cart getCart() {
        Cart cart = new Cart();
        if(isLogin()){
            mergeCart();
        }
       cart.setItems(getCartItemList(createBoundHashOps()));
        return cart;
    }

    @Override
    public List<CartItem> getCheckedCartItemList() {
        List<CartItem> cartItemList = getCartItemList(createBoundHashOps());
        if (cartItemList==null||cartItemList.size()==0) {
            return null;
        }
        List<CartItem> collect = cartItemList.stream().filter(item -> {
            return item.getCheck();
        }).map(item -> {
            SkuInfoVo skuInfo = getSkuInfo(item.getSkuId());
            if (skuInfo!=null){
                item.setPrice(skuInfo.getPrice());
            }
            return item;
        }).collect(Collectors.toList());
        return collect;
    }


    private List<CartItem> getCartItemList(BoundHashOperations<String, Object, Object> boundHashOps){
        List<Object> values = boundHashOps.values();
        List<CartItem> items = null;
        if (values!=null&&values.size()>0){
            items = values.stream().map(v -> {
                return JSON.parseObject((String) v,CartItem.class);
            }).collect(Collectors.toList());
        }
        return items;
    }

    private void mergeCart(){
        UserInfoTo userInfoTo = CartInterceptor.userInfoToThreadLocal.get();
        String tempKey = CartConstant.CART_SAVE_PREFIX+userInfoTo.getUserKey();
        BoundHashOperations<String, Object, Object> boundHashOps = createBoundHashOps(tempKey);
        List<CartItem> itemList = getCartItemList(boundHashOps);
        if (itemList!=null){
            for (CartItem cartItem : itemList) {
                addCartItem(cartItem);
            }
            redisTemplate.delete(tempKey);
        }
    }



    private boolean isLogin(){
        UserInfoTo userInfoTo = CartInterceptor.userInfoToThreadLocal.get();
        return userInfoTo.getUserId()!=null;
    }

    private String getCustomerKey(){
        UserInfoTo userInfoTo = CartInterceptor.userInfoToThreadLocal.get();
        String customerKey = "";
        if(userInfoTo.getUserId()!=null){
            customerKey = CartConstant.CART_SAVE_PREFIX+userInfoTo.getUserId().toString();
        }else {
            customerKey = CartConstant.CART_SAVE_PREFIX+userInfoTo.getUserKey();
        }
        return customerKey;
    }

    private BoundHashOperations<String, Object, Object> createBoundHashOps(){
        UserInfoTo userInfoTo = CartInterceptor.userInfoToThreadLocal.get();
        String customerKey = getCustomerKey();

        return redisTemplate.boundHashOps(customerKey);
    }

    private BoundHashOperations<String, Object, Object> createBoundHashOps(String customerKey){
        UserInfoTo userInfoTo = CartInterceptor.userInfoToThreadLocal.get();
        return redisTemplate.boundHashOps(customerKey);
    }

    private SkuInfoVo getSkuInfo(Long skuId){
        R result = productFeignService.getSkuInfo(skuId);
        Map JSONMap = (Map) result.get("skuInfo");
        String jsonString = JSON.toJSONString(JSONMap);
        return JSON.parseObject(jsonString, new TypeReference<SkuInfoVo>(){});
    }

    private CartItem createItem(Long skuId, Integer count) throws ExecutionException, InterruptedException {
        CartItem cartItem = new CartItem();
        CompletableFuture<Void> skuInfoFuture = CompletableFuture.runAsync(() -> {
            SkuInfoVo skuInfoVo = getSkuInfo(skuId);
            cartItem.setCheck(true);
            cartItem.setCount(count);
            cartItem.setImage(skuInfoVo.getSkuDefaultImg());
            cartItem.setPrice(skuInfoVo.getPrice());
            cartItem.setSkuId(skuInfoVo.getSkuId());
            cartItem.setPrice(skuInfoVo.getPrice());
            cartItem.setTitle(skuInfoVo.getSkuTitle());
            cartItem.setName(skuInfoVo.getSkuName());
        }, executor);

        CompletableFuture<Void> attrListFuture = CompletableFuture.runAsync(() -> {
            List<String> attrList = productFeignService.getSkuSaleAttrList(skuId);
            cartItem.setSkuAttr(attrList);
        }, executor);
        CompletableFuture.allOf(skuInfoFuture,attrListFuture).get();
        return cartItem;
    }

    private CartItem updateItem(String cartItemStr, Integer count){
        CartItem cartItem = JSON.parseObject(cartItemStr, new TypeReference<CartItem>(){});
        cartItem.setCount(cartItem.getCount()+count);
        return cartItem;
    }
}
